package com.su.gulimall.cart.interceptor;

import com.su.common.constant.CartConstant;
import com.su.common.vo.MemberRespVo;
import com.su.gulimall.cart.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


//判断用户的状态

public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoVo> threadLocal =new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoVo infoVo = new UserInfoVo();
        //这里面的东西都在redis中
        HttpSession session = request.getSession();
        MemberRespVo loginUser = (MemberRespVo) session.getAttribute("loginUser");
        //判断用户是否登录，如果登录，修改判断状态类
        if(loginUser!=null)
        {
            infoVo.setUserId(loginUser.getId());
        }
        //判断是否拥有临时身份,如果拥有临时身份，将其值放入状态类中
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0)
        {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    infoVo.setUserKey(cookie.getValue());
                    //是否拥有临时身份设置为true
                    infoVo.setHasCookie(true);
                }
            }
        }
        //如果没有临时身份，统一安排临时身份,即创建临时身份
        if(infoVo.getUserKey()==null)
        {
            String uuid= UUID.randomUUID().toString().replace("-","");
            infoVo.setUserKey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(infoVo);
        return true;
    }
    //如果临时用户没有保存在cookies中，保存该临时用户，并设置过期时间
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoVo infoVo = threadLocal.get();
        if(!infoVo.getHasCookie()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, infoVo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
